from django.shortcuts import render
from django.http import HttpResponse
import json
from result.result_code import ajaxResult
import uuid as create_uuid
from . import test_fake
from appointment_app.service import user_check_task_service
from appointment_app.service import check_place_service, group_check_task_service
from django.core.paginator import Paginator
from common import DateTimeUtil

###################### wx-app api ############################
# 根据省、市、区、县、坐标获取检测地点
def get_places(request):
    res_obj_dic_list = []
    queryForm = {}
    if request.method == "GET":
        queryForm["longitude"] = request.GET.get("longitude", "")
        queryForm["latitude"] = request.GET.get("latitude", "")
        queryForm["province"] = request.GET.get("province", "")
        queryForm["city"] = request.GET.get("city", "")
        queryForm["region"] = request.GET.get("region", "")
        queryForm["street"] = request.GET.get("street", "")
        queryForm["place_name"] = request.GET.get("place_name", "")
    res_obj_list = check_place_service.getCheckPlaceList(queryForm)
    if res_obj_list:
        for res_obj in res_obj_list:
            res_obj_dic = {}
            res_obj_dic["uuid"] = res_obj.uuid
            res_obj_dic["longitude"] = res_obj.longitude
            res_obj_dic["latitude"] = res_obj.latitude
            res_obj_dic["province"] = res_obj.province
            res_obj_dic["city"] = res_obj.city
            res_obj_dic["region"] = res_obj.region
            res_obj_dic["street"] = res_obj.street
            res_obj_dic["place_name"] = res_obj.place_name
            res_obj_dic_list.append(res_obj_dic)
    res = {"code": 0, "places": res_obj_dic_list}
    return HttpResponse(json.dumps(res))


# 用户 根据 检测点 place_uuid 查询 集体检测任务
def get_tasks_by_place(request):
    res_obj_dic = {}
    res_obj_dic_list = []
    place_uuid = request.GET.get("place_uuid", 0)
    res_obj_list = group_check_task_service.getGroupCheckTaskByPlaceUuid(place_uuid)
    if res_obj_list:
        for res_obj in res_obj_list:
            res_obj_dic["uuid"] = res_obj.uuid
            res_obj_dic["time_start"] = DateTimeUtil.datatime_to_sub(res_obj.time_start)
            res_obj_dic["time_end"] = DateTimeUtil.datatime_to_sub(res_obj.time_end)
            res_obj_dic["duration"] = res_obj.duration
            res_obj_dic["sum_num"] = res_obj.sum_num
            res_obj_dic["used_num"] = res_obj.used_num
            res_obj_dic["used_and_sum_num"] = (
                str(res_obj.used_num) + "/" + str(res_obj.sum_num)
            )
            res_obj_dic["place_all_name"] = check_place_service.getCheckPlaceAllName(
                res_obj.place_uuid
            )
            res_obj_dic["limit_order_time"] = DateTimeUtil.datatime_to_sub(
                res_obj.limit_order_time
            )
            res_obj_dic_list.append(res_obj_dic)
    res = {"code": 0, "tasks": res_obj_dic_list}
    return HttpResponse(json.dumps(res))


# 用户根据user_uuid,group_check_uuid预约检测任务
def order_group_check(request):
    res_one = {}
    user_check_task_dic = {}
    res = {"code": 1, "task": res_one}
    if request.method == "POST":
        body_unicode = request.body.decode("utf-8")
        params = json.loads(body_unicode)
        user_check_task_dic["uuid"] = create_uuid.uuid4()  # 检测任务id
        user_check_task_dic["group_check_uuid"] = group_check_uuid = params.get("group_check_uuid", "")
        user_check_task_dic["user_uuid"] = params.get("user_uuid", "")
        user_check_task_dic["sign_in_time"] = DateTimeUtil.current_time_str()
        user_check_task_dic["order_time"] = ""
        is_order = group_check_task_service.updateUsedNumByUuid(group_check_uuid)
        # 如果可预约
        if is_order:
            res_obj = user_check_task_service.order_group_check(user_check_task_dic)
            if res_obj:
                res = {"code": 0, "task": res_one}
    return HttpResponse(json.dumps(res))

# 根据user_uuid查询预约的检测任务
def query_order_history(request):
    res_list = []
    user_uuid = request.GET.get("user_uuid", "")
    res_list_obj = user_check_task_service.query_order_history(user_uuid)
    if res_list_obj:
        for rlo in res_list_obj:
            res_one = {}
            res_one["uuid"] = rlo.uuid
            res_one["user_uuid"] = rlo.user_uuid
            res_one["sign_in_time"] = DateTimeUtil.datatime_to_sub(rlo.sign_in_time)
            res_one["order_time"] = DateTimeUtil.datatime_to_sub(rlo.order_time)
            res_one["group_check_uuid"] = rlo.group_check_uuid
            res_one["state"] = rlo.state
            group_check_uuid = rlo.group_check_uuid
            # 根据group_check_uuid查询预约检测组信息
            group_check_obj = group_check_task_service.getGroupCheckTask(
                group_check_uuid
            )
            if group_check_obj:
                res_one["time_start"] = DateTimeUtil.datatime_to_sub(
                    group_check_obj.time_start
                )
                res_one["time_end"] = DateTimeUtil.datatime_to_sub(
                    group_check_obj.time_end
                )
                res_one["duration"] = group_check_obj.duration
                res_one["sum_num"] = group_check_obj.sum_num
                res_one["used_num"] = group_check_obj.used_num
                res_one["place_uuid"] = group_check_obj.place_uuid
                res_one["limit_order_time"] = DateTimeUtil.datatime_to_sub(
                    group_check_obj.limit_order_time
                )
            res_list.append(res_one)
    res = {"code": 0, "orders": res_list}
    return HttpResponse(json.dumps(res))
# 更新个人预约任务的状态
def user_check_task_state(request):
    res = {'code': 0, 'msg': {}}
    if request.method == 'PUT':
        data = json.loads(request.body)
        print(data)
        uuid = data.uuid

    return HttpResponse(json.dumps(res))

###################### web api ############################
# 查询检测地点
def getCheckPlaceList(request):
    queryForm = {}
    pageNum = request.POST.get("pageNum", 0)
    pageSize = request.POST.get("pageSize", 0)
    queryForm["longitude"] = ""
    queryForm["latitude"] = ""
    queryForm["province"] = request.POST.get("province", "")
    queryForm["city"] = request.POST.get("city", "")
    queryForm["region"] = request.POST.get("region", "")
    queryForm["street"] = request.POST.get("street", "")
    queryForm["place_name"] = request.POST.get("place_name", "")
    resultList = []
    total = 0
    res_obj = check_place_service.getCheckPlaceList(queryForm)
    if res_obj:
        # 创建分页对象
        ptr = Paginator(res_obj, pageSize)
        total = ptr.count
        # 获取当前页数据
        current_res = ptr.page(pageNum)
        for r in current_res:
            result = {}
            result["uuid"] = r.uuid
            result["province"] = r.province
            result["city"] = r.city
            result["region"] = r.region
            result["street"] = r.street
            result["place_name"] = r.place_name
            result["lon_lat"] = r.longitude + "," + r.latitude
            result["createBy"] = "admin"
            result["pcrs"] = [r.province, r.city, r.region, r.street]
            resultList.append(result)
    return ajaxResult("success", {"data": resultList, "total": total}, "查询成功")


# 根据uuid 查询监测点
def getCheckPlaceByUuid(request):
    result = {}
    uuid = request.GET.get("uuid", 0)
    res_obj = check_place_service.getCheckPlaceByUuid(uuid)
    if res_obj:
        result["uuid"] = res_obj.uuid
        result["province"] = res_obj.province
        result["city"] = res_obj.city
        result["region"] = res_obj.region
        result["street"] = res_obj.street
        result["place_name"] = res_obj.place_name
        result["pcrs"] = [
            res_obj.province,
            res_obj.city,
            res_obj.region,
            res_obj.street,
        ]
    return ajaxResult("success", {"data": result}, "查询成功")


# 根据pccs 省、市、区、街道查询检测点信息
def getcheckPlaceByPcrs(request):
    resultList = []
    province = request.GET.get("province", 0)
    city = request.GET.get("city", 0)
    region = request.GET.get("region", 0)
    street = request.GET.get("street", 0)
    res_obj = check_place_service.getcheckPlaceByPcrs(province, city, region, street)
    if res_obj:
        for r in res_obj:
            result = {}
            result["value"] = r.uuid
            result["label"] = r.place_name
            resultList.append(result)
    return ajaxResult("success", {"data": resultList}, "添加成功")


# 增加预约检测点
def addCheckPlace(request):
    formData = {}
    formData["uuid"] = create_uuid.uuid4()
    formData["province"] = request.POST.get("province", 0)
    formData["city"] = request.POST.get("city", 0)
    formData["region"] = request.POST.get("region", 0)
    formData["street"] = request.POST.get("street", 0)
    formData["place_name"] = request.POST.get("place_name", 0)
    res = check_place_service.addCheckPlace(formData)
    return ajaxResult("success", {}, "添加成功")


# 更新预约检测点
def updateCheckPlace(request):
    formData = {}
    formData["uuid"] = request.POST.get("uuid", 0)
    formData["province"] = request.POST.get("province", 0)
    formData["city"] = request.POST.get("city", 0)
    formData["region"] = request.POST.get("region", 0)
    formData["street"] = request.POST.get("street", 0)
    formData["place_name"] = request.POST.get("place_name", 0)
    res = check_place_service.updateCheckPlace(formData)
    return ajaxResult("success", {}, "更新成功")


# 删除检预约检测点
def delCheckPlace(request):
    result = {}
    uuid = request.GET.get("uuid", 0)
    res = check_place_service.delCheckPlace(uuid)
    return ajaxResult("success", {}, "删除成功")


############################
# 查询检测任务组
def getGroupCheckTaskList(request):
    resultList = []
    queryForm = {}
    pageNum = request.POST.get("pageNum", 0)
    pageSize = request.POST.get("pageSize", 0)
    queryForm["province"] = request.POST.get("province", "")
    queryForm["city"] = request.POST.get("city", "")
    queryForm["region"] = request.POST.get("region", "")
    queryForm["street"] = request.POST.get("street", "")
    queryForm["place_name"] = request.POST.get("place_name", "")
    total = 0
    res_obj = group_check_task_service.getGroupCheckTaskList(queryForm)
    if res_obj:
        # 创建分页对象
        ptr = Paginator(res_obj, pageSize)
        total = ptr.count
        # 获取当前页数据
        current_res = ptr.page(pageNum)
        for r in current_res:
            result = {}
            result["uuid"] = r.uuid
            result["time_start"] = r.time_start
            result["time_end"] = r.time_end
            result["duration"] = r.duration
            result["used_and_sum_num"] = str(r.used_num) + "/" + str(r.sum_num)
            result["place_all_name"] = check_place_service.getCheckPlaceAllName(
                r.place_uuid
            )
            result["limit_order_time"] = r.limit_order_time
            resultList.append(result)
    return ajaxResult("success", {"data": resultList, "total": total}, "添加成功")


# 增加检测任务组
def addGroupCheckTask(request):
    formData = {}
    formData["uuid"] = create_uuid.uuid4()
    formData["time_start"] = request.POST.get("time_start", 0)
    formData["time_end"] = request.POST.get("time_end", 0)
    formData["sum_num"] = request.POST.get("sum_num", 0)
    formData["duration"] = request.POST.get("duration", 0)
    formData["place_uuid"] = request.POST.get("place_uuid", 0)
    formData["limit_order_time"] = request.POST.get("limit_order_time", 0)
    res = group_check_task_service.addGroupCheckTask(formData)
    return ajaxResult("success", {}, "添加成功")


# 更新检测任务组
def updateGroupCheckTask(request):
    formData = {}
    formData["uuid"] = request.POST.get("uuid", 0)
    formData["time_start"] = request.POST.get("time_start", 0)
    formData["time_end"] = request.POST.get("time_end", 0)
    formData["sum_num"] = request.POST.get("sum_num", 0)
    formData["duration"] = request.POST.get("duration", 0)
    formData["place_uuid"] = request.POST.get("place_uuid", 0)
    formData["limit_order_time"] = request.POST.get("limit_order_time", 0)
    res = group_check_task_service.updateGroupCheckTask(formData)
    return ajaxResult("success", {}, "更新成功")


# 根据uuid查询检测任务组
def getGroupCheckTask(request):
    result = {}
    uuid = request.GET.get("uuid", 0)
    res_obj = group_check_task_service.getGroupCheckTask(uuid)
    if res_obj:
        result["uuid"] = res_obj.uuid
        result["time_start"] = res_obj.time_start
        result["time_end"] = res_obj.time_end
        result["duration"] = res_obj.duration
        result["sum_num"] = res_obj.sum_num
        result["used_num"] = res_obj.used_num
        pcrs, place_name = check_place_service.getCheckPlaceAllName(res_obj.place_uuid)
        result["province"] = pcrs[0]
        result["city"] = pcrs[1]
        result["region"] = pcrs[2]
        result["street"] = pcrs[3]
        result["place_name"] = place_name
        result["pcrs"] = pcrs
        result["place_uuid"] = res_obj.place_uuid
        result["limit_order_time"] = res_obj.limit_order_time
    return ajaxResult("success", {"data": result}, "查询成功")


# 删除任务组数据
def delGroupCheckTask(request):
    result = {}
    uuid = request.GET.get("uuid", 0)
    res = group_check_task_service.delGroupCheckTask(uuid)
    return ajaxResult("success", {}, "删除成功")
